package com.jd.myaaaccount;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.jd.myaaaccount.util.BitmapHelper;
import com.jd.myaaaccount.util.OperateCode;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;

public class CaptureActivity extends BaseActivity {

	private SurfaceView svMain;
	private SurfaceHolder holder;

	private Button btnCapture;

	private int w, h;

	Camera camera;
	private boolean isPreview = false;

	Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_capture);
		initControl();

		WindowManager wm = getWindowManager();
		Display display = wm.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		display.getMetrics(metrics);
		w = 500;// metrics.widthPixels;
		h = 800;// metrics.heightPixels;
		holder = svMain.getHolder();
		holder.addCallback(new Callback() {

			@Override
			public void surfaceDestroyed(SurfaceHolder arg0) {
				// TODO Auto-generated method stub
				if (camera != null) {
					if (isPreview) {
						camera.stopPreview();
					}
					camera.release();
					camera = null;
				}
			}

			@Override
			public void surfaceCreated(SurfaceHolder arg0) {
				initCamera();
			}

			@Override
			public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
					int arg3) {

			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == OperateCode.CAPTURE) {
					Intent intent = new Intent();
					intent.putExtra("bmp", (byte[]) msg.obj);
					setResult(1, intent);
					finish();
				}
			}
		};

		btnCapture.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				capture();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.capture, menu);
		return true;
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		setResult(RESULT_OK, intent);

		super.onBackPressed();
	}

	private void initControl() {
		svMain = (SurfaceView) findViewById(R.id.svMain);
		btnCapture = (Button) findViewById(R.id.btnCapture);
	}

	private void initCamera() {
		if (!isPreview) {
			camera = android.hardware.Camera.open();
			camera.setDisplayOrientation(90);
		}
		if (camera != null && !isPreview) {
			try {
				Camera.Parameters param = camera.getParameters();
				// 选择合适的预览尺寸
				List<Camera.Size> sizeList = param.getSupportedPreviewSizes();
				if (sizeList.size() > 0) {
					param.setPreviewSize(sizeList.get(0).width,
							sizeList.get(0).height);
					param.setPictureSize(sizeList.get(0).width,
							sizeList.get(0).height);
				}
				param.setPictureFormat(ImageFormat.JPEG);
				param.set("jpeg-quality", 85);
				camera.setParameters(param);
				camera.setPreviewDisplay(holder);
				camera.startPreview();
				setAutoFocus();
			} catch (Exception e) {
				e.printStackTrace();
			}
			isPreview = true;
		}
	}

	private void setAutoFocus() {
		camera.autoFocus(new AutoFocusCallback() {

			@Override
			public void onAutoFocus(boolean arg0, Camera arg1) {
				if (arg0) {

				}
			}
		});
	}

	private void capture() {
		camera.takePicture(new ShutterCallback() {

			@Override
			public void onShutter() {

			}
		}, new PictureCallback() {

			@Override
			public void onPictureTaken(byte[] arg0, Camera arg1) {

			}
		}, new PictureCallback() {

			@Override
			public void onPictureTaken(byte[] arg0, Camera arg1) {
				Message msg = new Message();
				msg.what = OperateCode.CAPTURE;
				msg.obj = BitmapHelper.compressPiture(arg0);
				handler.sendMessage(msg);
			}
		});
	}

	private void savePicture(String fileName, Bitmap bmp) {
		File file = new File(Environment.getExternalStorageDirectory(),
				fileName);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			bmp.compress(CompressFormat.JPEG, 100, fos);
			fos.close();
		} catch (Exception e) {

		}
	}

	/**
	 * 根据路径获取图片资源（已缩放）
	 * 
	 * @param url
	 *            图片存储路径
	 * @param width
	 *            缩放的宽度
	 * @param height
	 *            缩放的高度
	 * @return
	 */
	private Bitmap getBitmapFromUrl(String url, double width, double height) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 设置了此属性一定要记得将值设置为false
		Bitmap bitmap = BitmapFactory.decodeFile(url);
		// 防止OOM发生
		options.inJustDecodeBounds = false;
		int mWidth = bitmap.getWidth();
		int mHeight = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = 1;
		float scaleHeight = 1;
		// try {
		// ExifInterface exif = new ExifInterface(url);
		// String model = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// 按照固定宽高进行缩放
		// 这里希望知道照片是横屏拍摄还是竖屏拍摄
		// 因为两种方式宽高不同，缩放效果就会不同
		// 这里用了比较笨的方式
		if (mWidth <= mHeight) {
			scaleWidth = (float) (width / mWidth);
			scaleHeight = (float) (height / mHeight);
		} else {
			scaleWidth = (float) (height / mWidth);
			scaleHeight = (float) (width / mHeight);
		}
		// matrix.postRotate(90); /* 翻转90度 */
		// 按照固定大小对图片进行缩放
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight,
				matrix, true);
		// 用完了记得回收
		bitmap.recycle();
		return newBitmap;
	}
}
